<?php

namespace apiend\modules\work\models;

use Yii;
use yii\db\Exception;
use common\models\work\Staff;
use common\logics\cascader\CompanyLogic;

/**
 * 预约模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class StaffForm extends \common\base\FormModel {

    /**
     * @var string 数据原型模型
     */
    protected $modelClass = Staff::class;

    /**
     * @var string 姓名
     */
    public $realname;

    /**
     * @var string 手机号
     */
    public $mobile;

    /**
     * @var string 职位
     */
    public $company_id;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['company_id'], 'integer'],
            [['realname', 'mobile', 'company_id'], 'required'],
            [['realname'], 'string', 'max' => 50],
            [['mobile'], 'string', 'max' => 11],
            ['mobile', '\common\validators\MobileValidator'],
            ['mobile', 'validateUniqueMobile'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'realname' => '姓名',
            'mobile' => '手机号',
            'company_id' => '单位',
        ];
    }

    /**
     * 校验唯一手机号
     * @param string $attribute the attribute currently being validated
     */
    public function validateUniqueMobile($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $mobile = $this->$attribute;
        $mobileOccupied = Staff::findByMobile($mobile)->andWhere([
            '!=', 'id', $this->id
        ])->exists();
        if ($mobileOccupied) {
            return $this->addError($attribute, '您输入的手机号已被占用，不能使用当前手机号');
        }
    }

    /**
     * 保存预约人员信息
     * @return boolean
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $model = $this->getModel();
        $model->setAttributes([
            'realname' => $this->realname,
            'company_id' => (int) $this->company_id,
        ]);
        if ($model->isNewRecord) {
            $model->status = Staff::STATUS_DEFAULT;
        }
        $model->setMobile($this->mobile);
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $model;
    }

    /**
     * {@inheritdoc}
     */
    public function setExtraAttributes($model) {
        if (!$model->isNewRecord) {
            $this->mobile = $model->fullMobile;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCompanyList() {
        $companyId = Yii::$app->user->identity->companyId;
        return CompanyLogic::findDeeps($companyId)->all();
    }

    /**
     * @inheritdoc
     */
    public function getSafeAttributes() {
        $attributes = $this->attributes();
        return array_values($attributes);
    }

    /**
     * {@inheritdoc}
     */
    public function getFormFields() {
        return $this->attributes;
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'form' => 'formFields',
            'companys' => function() {
                return $this->companyList;
            },
        ];
    }

}
